package com.example.controller;

import com.example.controller.results.Code;
import com.example.controller.results.Result;
import com.example.domain.User;
import com.example.service.UserService;
import com.example.system.exception.BusinessException;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author Li Cheng
 * @Date 2021/6/27 21:36
 * @Version 1.0
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/{id}")
    public Result getUser(@PathVariable Integer id){
        User user = userService.get(id);
        if (id==10){
            throw new BusinessException("查询出错了",Code.GET_ERROR);
        }
        return new Result(null != user ? Code.GET_OK:Code.GET_ERROR,user);
    }

    @PostMapping
    public Result save(User user){

        boolean flag = userService.save(user);
        return new Result(flag? Code.SAVE_OK:Code.SAVE_ERROR);

    }


    @PutMapping
    public Result update(User user){

        boolean flag = userService.update(user);
        return new Result(flag? Code.UPDATE_OK:Code.UPDATE_ERROR);


    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id){
        boolean flag = userService.delete(id);
        return new Result(flag ? Code.DELETE_OK : Code.DELETE_ERROR);
    }


    @GetMapping("/{page}/{size}")
    public Result getAll(@PathVariable Integer page, @PathVariable Integer size){
        PageInfo<User> all = userService.getAll(page, size);
        return new Result(null != all ? Code.GET_OK:Code.GET_ERROR,all);

    }






}
